﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using CDV.MC.MatrixDriver.WebApp.Filter;
using CDV.MC.MatrixDriver.WebApp.Service;
using CDV.MC.MatrixDriver.WebApp.Data;
using CDV.MC.MatrixDriver.WebApp.Extensions;

namespace CDV.MC.MatrixDriver.WebApp.Controllers
{
    [LoginFilter]
    public class ClientController : Controller
    {
        public IActionResult Index()
        {
            var clientInfo = GetClients();
            return View("ClientView", clientInfo);
        }


        public IList<ClientInfo> GetClients()
        {
            var httpClientProvider = (IHttpClientProvider)ServiceLocator.Instance.GetService(typeof(IHttpClientProvider));

            using (var httpClient = httpClientProvider.GetHttpClient(HttpContext))
            {
                var clientInfo = httpClient.Get<IList<ClientInfo>>("matrix", "GetClients");

                var selfAddress = httpClient.GetRemotingIP();
                var self = clientInfo.FirstOrDefault(client => $"{client.IP}:{client.Port}" == selfAddress);
                if (self != null)
                {
                    self.Self = true;
                }
                return clientInfo;
            }
        }
    }
}